package com.dries.portal.module.xxshop.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dries.common.exception.ApiException;
import com.dries.portal.module.convener.entity.Convener;
import com.dries.portal.module.convener.entity.JoinConvener;
import com.dries.portal.module.convener.enums.ConvenerPaymentType;
import com.dries.portal.module.convener.enums.ConvenerStatus;
import com.dries.portal.module.convener.enums.JoinConvenerType;
import com.dries.portal.module.convener.service.IConvenerService;
import com.dries.portal.module.convener.service.IJoinConvenerService;
import com.dries.portal.module.convener.service.impl.OrderPaySmsSender;
import com.dries.portal.module.convener.vo.ConvenerVo;
import com.dries.portal.module.convener.vo.ShopDetailVo;
import com.dries.portal.module.user.entity.UserEntity;
import com.dries.portal.module.user.service.UserService;
import com.dries.portal.module.wechat.wxma.service.IWeChatService;
import com.dries.portal.module.wechat.wxma.vo.OrderPayMsgVo;
import com.dries.portal.module.xxshop.entity.Actgoods;
import com.dries.portal.module.xxshop.entity.Goods;
import com.dries.portal.module.xxshop.entity.Userorder;
import com.dries.portal.module.xxshop.entity.Userordergoods;
import com.dries.portal.module.xxshop.enums.OrderEnums;
import com.dries.portal.module.xxshop.mapper.UserorderMapper;
import com.dries.portal.module.xxshop.service.IGoodsService;
import com.dries.portal.module.xxshop.service.IUserorderService;
import com.dries.portal.module.xxshop.service.IUserordergoodsService;
import com.dries.portal.module.xxshop.service.IXXshopActivityService;
import com.dries.portal.module.xxshop.vo.ShopActivityVo;
import com.dries.portal.module.xxshop.vo.UserOrderInfoVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@DS("xxshop")
@Service
public class UserorderServiceImpl extends ServiceImpl<UserorderMapper, Userorder> implements IUserorderService {

    @Resource
    private OrderPaySmsSender orderPaySmsSender;
    @Resource
    private UserService userService;
    @Resource
    private IUserordergoodsService userordergoodsService;
    @Resource
    private IXXshopActivityService shopActivityService;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private IUserorderService userorderService;
    @Resource
    private IConvenerService convenerService;
    @Resource
    private IJoinConvenerService joinConvenerService;
    @Resource
    private IWeChatService weChatService;

    @Override
    public UserOrderInfoVo getOrderInfoByOrderId(Long orderid) {

        UserOrderInfoVo orderInfoVo = new UserOrderInfoVo();

        Userorder byId = getById(orderid);
        BeanUtils.copyProperties(byId, orderInfoVo);

        List<Userordergoods> userordergoods = userordergoodsService.list(new QueryWrapper<Userordergoods>().lambda().eq(Userordergoods::getOrderid, orderid));

        if (CollUtil.isNotEmpty(userordergoods)) {
            orderInfoVo.setOrderDetail(userordergoods);
        }


        ConvenerVo convener;
        if (byId.getOrderpid() != 0) {
            convener = convenerService.getConvenerInfoByOrderId(byId.getOrderpid());
        } else {
            convener = convenerService.getConvenerInfoByOrderId(orderid);
        }

        orderInfoVo.setConverter(convener);
        // 2 获取召集令参与人
        List<JoinConvener> joinConveners = joinConvenerService.list(new QueryWrapper<JoinConvener>().lambda()
                .eq(JoinConvener::getConvenerId, convener.getCid())
                .eq(JoinConvener::getStatus, JoinConvenerType.SIGNUP.getCode())
        );

        orderInfoVo.setJoinConveners(joinConveners);

        return orderInfoVo;
    }

    @Override
    public UserOrderInfoVo getOrderInfoByUserId(Long orderId, Long userId) {
        UserOrderInfoVo orderInfoVo = new UserOrderInfoVo();

        Userorder userorder = null;

        userorder = getOne(new QueryWrapper<Userorder>().lambda()
                    .eq(Userorder::getOrderpid, orderId)
                    .eq(Userorder::getUserid, userId)
            );
        if (userorder == null) {
            userorder = getById(orderId);
        }

        if (userorder != null) {
            BeanUtils.copyProperties(userorder, orderInfoVo);

            List<Userordergoods> userordergoods = userordergoodsService.list(new QueryWrapper<Userordergoods>().lambda().eq(Userordergoods::getOrderid, userorder.getOrderpid()));

            if (CollUtil.isNotEmpty(userordergoods)) {
                orderInfoVo.setOrderDetail(userordergoods);
            }

            LambdaQueryWrapper<Convener> wrapper = new QueryWrapper<Convener>().lambda();
            if (userorder.getOrderpid() != 0) {
                Userorder byId1 = getById(userorder.getOrderpid());
                wrapper.eq(Convener::getOrderId, byId1.getOrderid());
            } else {
                wrapper.eq(Convener::getOrderId, orderId);
            }
            Convener convener = convenerService.getOne(wrapper);
            // 2 获取召集令参与人
            List<JoinConvener> joinConveners = joinConvenerService.list(new QueryWrapper<JoinConvener>().lambda()
                    .eq(JoinConvener::getConvenerId, convener.getCid())
                    .eq(JoinConvener::getStatus, JoinConvenerType.SIGNUP.getCode())
            );

            orderInfoVo.setJoinConveners(joinConveners);
        }

        return orderInfoVo;
    }

    @Override
    public UserOrderInfoVo createOrderByConvener(Convener convener) {

        if (!convener.getConvenerStatus().equals(ConvenerStatus.NORMAL.getCode())) {
            throw new ApiException("召集令状态错误");
        }

        if (convener.getOrderId() != null) {
            return userorderService.getOrderInfoByOrderId(convener.getOrderId());
        }

        // 1 获取活动信息
        ShopActivityVo shopActivity = shopActivityService.getShopActivityInfoById(convener.getActivityId());
        // 2 获取召集令参与人
        List<JoinConvener> joinConveners = joinConvenerService.list(new QueryWrapper<JoinConvener>().lambda()
                .eq(JoinConvener::getConvenerId, convener.getCid())
                .eq(JoinConvener::getStatus, JoinConvenerType.SIGNUP.getCode())
        );

        // 3.创建主订单
        String currTime = String.valueOf(System.currentTimeMillis());
        String orderId = RandomUtil.randomNumbers(6) + currTime;
        log.info("获取当前时间====》{}，生成当前订单ID====》{}", currTime, orderId);
        // 3.1 召集令绑定订单ID
        convener.setOrderId(Long.parseLong(orderId));
        convenerService.updateById(convener);

        // 3.2 组装订单信息
        Userorder userorder = new Userorder();
        userorder.setShopid(convener.getShopId());
        userorder.setUserid(convener.getUserId());
        // 收货地址
        userorder.setAddrid(0L);
        userorder.setOrderid(Long.parseLong(orderId));
        userorder.setOrdersn(orderId);
        userorder.setPaytype(1);
        // 支付类型
        userorder.setOrdertype(1);
        // 订单状态
        userorder.setStatus(OrderEnums.OrderStatusType.UNPAID.getCode());
        // 是否评论
        userorder.setIscomment(0);
        // 是否需要发票
        userorder.setIsneedinvoice(1);
        // 优惠券ID
        userorder.setUtickid(0L);
        // 订单流程完成度
        userorder.setIsover(0);
        userorder.setWrtime(new Date());
        // 订单总金额
        double priceTotal = shopActivity.getActgoods().stream().mapToDouble(Actgoods::getGoodsprice).sum();
        //        BigDecimal reduce = shopActivity.getActgoods().stream()
        //                .map(actgoods -> new BigDecimal(Double.toString(actgoods.getGoodsprice())).multiply(new BigDecimal(Double.toString(actgoods.getGoodslimit()))))
        //                .reduce(BigDecimal.ZERO, BigDecimal::add);
        //        userorder.setPricetotal(reduce.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        userorder.setPricetotal(priceTotal);
        //TODO 实际支付金额
        if (Objects.equals(convener.getPaymentType(), ConvenerPaymentType.AA.getCode())) {
            BigDecimal priceTotal1 = new BigDecimal(Double.toString(priceTotal));
            BigDecimal divide = priceTotal1.divide(new BigDecimal(joinConveners.size()), 2, BigDecimal.ROUND_UP);
            userorder.setPricepay(divide.doubleValue());
        } else {
            userorder.setPricepay(priceTotal);
        }
        userorderService.save(userorder);

        // 组装订单详细商品信息
        shopActivity.getActgoods().forEach(actgoods -> {
            Userordergoods userordergoods = new Userordergoods();
            String suffix = String.valueOf(System.currentTimeMillis());
            String orderGoodsId = RandomUtil.randomNumbers(6) + suffix;
            userordergoods.setOrdergoodsid(Long.valueOf(orderGoodsId));
            userordergoods.setOrderid(Long.valueOf(orderId));

            Goods goods = goodsService.getById(actgoods.getGoodsid());
            if (goods == null) {
                throw new ApiException("商品不存在或已下架");
            }
            if (goods.getStock() == 0) {
                throw new ApiException("商品已售罄");
            }

            userordergoods.setGoodsid(goods.getGoodsid());
            userordergoods.setGoodscount(1);
            userordergoods.setSoctt(goods.getGoodssoctt());
            userordergoods.setPrice(actgoods.getGoodsprice());
            userordergoods.setGoodsstatus(OrderEnums.OrderGoodsStatus.NORMAL.getCode());

            userordergoodsService.save(userordergoods);
        });

        // 2 创建子订单
        this.createOrder(userorder, joinConveners, convener);

        // TODO 3.发送短信通知支付订单
        orderPaySmsSender.send(convener.getMobile(), orderId);

        // 发送微信消息通知
        /**
         * 商家名称 thing9
         * 支付金额 amount3
         * 订单号 character_string7
         * 订单状态 phrase6
         * 温馨提示 thing1
         */
        String shopDetail = convener.getShopDetail();
        ShopDetailVo shopDetailVo;
        String shopName = "又享聚";
        if (StrUtil.isNotBlank(shopDetail)) {
             shopDetailVo = JSONUtil.toBean(shopDetail, ShopDetailVo.class);
             shopName = shopDetailVo.getShop_name();
        }
        UserEntity user = userService.getUserById(convener.getUserId()).getData();
        OrderPayMsgVo msgVo = new OrderPayMsgVo(
                user.getOpenid(), shopName, userorder.getPricepay().toString(), userorder.getOrderid().toString(), "待支付", "自助下单成功，请及时支付"
        );
        weChatService.orderPayWxMsgSender(msgVo);

        convener.setConvenerStatus(ConvenerStatus.UNDERWAY.getCode());
        convenerService.updateById(convener);

        return userorderService.getOrderInfoByOrderId(userorder.getOrderid());
    }

    @Override
    public void createOrder(Userorder userorder, List<JoinConvener> joinConveners, Convener convener) {

        joinConveners.forEach(joinConvener -> {
            if (!joinConvener.getUserId().equals(convener.getUserId())) {
                // 创建订单
                String currTime = String.valueOf(System.currentTimeMillis());
                String orderId = RandomUtil.randomNumbers(6) + currTime;
                log.info("获取当前时间====》{}，生成当前订单ID====》{}", currTime, orderId);

                // 组装订单信息
                Userorder userorderChildren = new Userorder();
                userorderChildren.setOrderpid(userorder.getOrderid());
                userorderChildren.setShopid(userorder.getShopid());
                userorderChildren.setUserid(joinConvener.getUserId());
                // 收货地址
                userorderChildren.setAddrid(0L);
                userorderChildren.setOrderid(Long.valueOf(orderId));
                userorderChildren.setOrdersn(orderId);
                userorderChildren.setPaytype(1);
                // 支付类型
                userorderChildren.setOrdertype(1);
                // 订单状态
                userorderChildren.setStatus(OrderEnums.OrderStatusType.UNPAID.getCode());
                // 是否评论
                userorderChildren.setIscomment(0);
                // 是否需要发票
                userorderChildren.setIsneedinvoice(1);
                // 优惠券ID
                userorderChildren.setUtickid(0L);
                // 订单流程完成度
                userorderChildren.setIsover(0);
                userorderChildren.setWrtime(new Date());
                // 订单总金额
                userorderChildren.setPricetotal(userorder.getPricetotal());
                //TODO 实际支付金额
                if (Objects.equals(convener.getPaymentType(), ConvenerPaymentType.AA.getCode())) {
                    BigDecimal priceTotal1 = new BigDecimal(Double.toString(userorder.getPricetotal()));
                    BigDecimal divide = priceTotal1.divide(new BigDecimal(joinConveners.size()), 2, BigDecimal.ROUND_DOWN);
                    userorderChildren.setPricepay(divide.doubleValue());
                } else {
                    userorderChildren.setPricepay(0.00);
                }

                userorderService.save(userorderChildren);
                // 发送短信消息通知支付
                orderPaySmsSender.send(joinConvener.getMobile(), orderId);

                String shopDetail = convener.getShopDetail();
                ShopDetailVo shopDetailVo;
                String shopName = "又享聚";
                if (StrUtil.isNotBlank(shopDetail)) {
                    shopDetailVo = JSONUtil.toBean(shopDetail, ShopDetailVo.class);
                    shopName = shopDetailVo.getShop_name();
                }
                UserEntity user = userService.getUserById(convener.getUserId()).getData();
                OrderPayMsgVo msgVo = new OrderPayMsgVo(
                        user.getOpenid(), shopName, userorderChildren.getPricepay().toString(), userorderChildren.getOrderid().toString(), "待支付", "自助下单成功，请及时支付"
                );

                weChatService.orderPayWxMsgSender(msgVo);

            }
        });
    }

    // 获取订单列表
    @Override
    public PageInfo<UserOrderInfoVo> orderList(Map<String, Object> params) {

        UserEntity user = userService.getCurrentUser().getData();
        LambdaQueryWrapper<Userorder> userorderWrapper = new QueryWrapper<Userorder>().lambda().eq(Userorder::getUserid, user.getUserid());
        String status = (String) params.get("status");
        if (StrUtil.isNotBlank(status)) {
            userorderWrapper.eq(Userorder::getStatus,status);
        }
        String pageSize = (String) params.get("pageSize");
        if (pageSize == null) {
            pageSize = "10";
        }
        String pageNum = (String) params.get("pageNum");
        if (pageNum == null) {
            pageNum = "1";
        }
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        List<Userorder> userorders = list(userorderWrapper);
        if (CollUtil.isNotEmpty(userorders)) {
            List<UserOrderInfoVo> collect = userorders.stream().map(userorder -> {
//                UserOrderInfoVo orderInfoVo = new UserOrderInfoVo();
//                BeanUtils.copyProperties(userorder, orderInfoVo);
//                List<Userordergoods> userordergoods = userordergoodsService.list(new QueryWrapper<Userordergoods>().lambda().eq(Userordergoods::getOrderid, userorder.getOrderid()));
//                if (CollUtil.isNotEmpty(userordergoods)) {
//                    orderInfoVo.setOrderDetail(userordergoods);
//                }
                return getOrderInfoByOrderId(userorder.getOrderid());
            }).collect(Collectors.toList());
            return new PageInfo<>(collect);
        }
        return new PageInfo<>(new ArrayList<>());
    }

}